const express = require('express');
// const routeFallback = require('connect-history-api-fallback');
const compression = require('compression');
const logger = require('morgan');
const path = require('path');
const devConfig = require('./webpack.config.dev');
const proConfig = require('./webpack.config.pro');

let env = process.env.NODE_ENV;
let output = env === 'production' ? proConfig.output : devConfig.output;
// const output = {
//     path: './',
//     publicPath: './'
// };

const router = express.Router();
const app = express();
const port = 8089;

// const mockApiRouter = require("./router-fake");

// 日志
app.use(logger('dev'));

// 开启压缩
app.use(compression());

//Mock路由
// app.use("/api", mockApiRouter);

// 页面路由fallback
// app.use(routeFallback());

// 静态资源
var options = {
  maxAge: 0
}

app.use('/read-article.html', function (req, res, next) {
  // console.log('read-article req', req.params);
  res.sendFile(path.resolve(__dirname, "build/read-article.html"), {
    cacheControl: false,
    maxAge: 0
  });
});

// app.use(express.static(path.resolve(__dirname, "build")));
app.use('/static', express.static(output.path + '/static', options));
app.use('/styles', express.static(output.path + '/styles', options));
app.use('/scripts', express.static(output.path + '/scripts', options));
app.use('/*', router);

router.get('/', function (req, res, next) {
  // console.log('/ req', req.params);
  res.sendFile(path.resolve(__dirname, "build/index.html"), {
    cacheControl: false,
    maxAge: 0
  });
});

app.use(function (req,  res,  next)  {
  var  err  =  new  Error('Not Found');  
  // console.log('404 req');
  err.status  =  404;  
  res.redirect('/');
  next(err);
});

// 启动服务
app.listen(port, (err) => {
  if (err) {
    return console.error(err);
  }

  console.log(`NODE_ENV:${env},服务启动，地址：http://localhost:${port}`);
});